package vn.com.vega.chacha.v2.widget;

import vn.com.vega.chacha.R;
import vn.com.vega.chacha.v2.Appinstant;
import vn.com.vega.chacha.v2.MainScreen;
import vn.com.vega.chacha.v2.PlayerScreen;
import vn.com.vega.chacha.v2.SplashScreen;
import vn.com.vega.chacha.v2.player.PlayerService;
import vn.com.vega.music.objects.Song;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.widget.RemoteViews;

/**
 * Simple widget to show currently playing album art along with play/pause and
 * next track buttons.
 */
public class ChaChaWidgetProvider extends AppWidgetProvider {
	static final String TAG = "ChaChaWidgetProvider";

	public static final String CMDAPPWIDGETUPDATE = "appwidgetupdate";
	public static final String CMDAPPWIDGETUPDATETHUMB = "addwidgetupdatethumb";
	public static final String IMAGE_URL = "thumb url";

	private static Song currentSong = null;

	private static ChaChaWidgetProvider sInstance;

	public static synchronized ChaChaWidgetProvider getInstance() {
		if (sInstance == null) {
			sInstance = new ChaChaWidgetProvider();
		}
		return sInstance;
	}

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		defaultAppWidget(context, appWidgetIds);

		// Send broadcast intent to any running MediaPlaybackService so it can
		// wrap around with an immediate update.
		Intent updateIntent = new Intent(PlayerService.SERVICECMD);
		updateIntent.putExtra(PlayerService.CMDNAME,
				ChaChaWidgetProvider.CMDAPPWIDGETUPDATE);
		updateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,
				appWidgetIds);
		updateIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
		context.sendBroadcast(updateIntent);
	}

	/**
	 * Initialize given widgets to default state, where we launch Music on
	 * default click and hide actions if service not running.
	 */
	private void defaultAppWidget(Context context, int[] appWidgetIds) {
		final RemoteViews views = new RemoteViews(context.getPackageName(),
				R.layout.chacha_widget);

		linkButtons(context, views, false /* not playing */);
		pushUpdate(context, appWidgetIds, views);
	}

	private void pushUpdate(Context context, int[] appWidgetIds,
			RemoteViews views) {
		// Update specific list of appWidgetIds if given, otherwise default to
		// all
		final AppWidgetManager gm = AppWidgetManager.getInstance(context);
		if (appWidgetIds != null) {
			gm.updateAppWidget(appWidgetIds, views);
		} else {
			gm.updateAppWidget(new ComponentName(context, this.getClass()),
					views);
		}
	}

	/**
	 * Check against {@link AppWidgetManager} if there are any instances of this
	 * widget.
	 */
	private boolean hasInstances(Context context) {
		AppWidgetManager appWidgetManager = AppWidgetManager
				.getInstance(context);
		int[] appWidgetIds = appWidgetManager
				.getAppWidgetIds(new ComponentName(context, this.getClass()));
		return (appWidgetIds.length > 0);
	}

	/**
	 * Handle a change notification coming over from {@link PlayerService}
	 */
	public void notifyChange(PlayerService service, String what) {
		if (hasInstances(service)) {
			if (PlayerService.META_CHANGED.equals(what)
					|| PlayerService.PLAYSTATE_CHANGED.equals(what)) {
				performUpdate(service, null);
			}
		}
	}

	private void sendRequestUpdateThumb(Context ctx, String imageUrl,
			int[] widgetIds) {
		Intent updateIntent = new Intent(PlayerService.SERVICECMD);
		updateIntent.putExtra(PlayerService.CMDNAME,
				ChaChaWidgetProvider.CMDAPPWIDGETUPDATETHUMB);
		updateIntent.putExtra(IMAGE_URL, imageUrl);
		updateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, widgetIds);
		updateIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
		ctx.sendBroadcast(updateIntent);
	}

	/**
	 * Update all active widget instances by pushing changes
	 */
	public void performUpdate(PlayerService service, int[] appWidgetIds) {
		final RemoteViews views = new RemoteViews(service.getPackageName(),
				R.layout.chacha_widget);
		// views.setBoolean(R.id.tv_title_artist, "setSelected", true);

		Song song = service.getCurrentSong();
		if (song == null) {
			currentSong = null;
			return;
		}
		if (currentSong == null || currentSong.id != song.id) {
			currentSong = song;
			if (currentSong.isLocalSong()) {
				views.setImageViewResource(R.id.widget_thumb, R.drawable.artist);
			} else {
				sendRequestUpdateThumb(service, currentSong.imageUrl, appWidgetIds);
			}
		}
		views.setTextViewText(R.id.tv_title_artist, song.title + " - "
				+ song.artist_name);

		// Set correct drawable for pause state
		final boolean playing = service.isPlaying();
		if (playing) {
			views.setImageViewResource(R.id.bt_pause_play_widget,
					R.drawable.bt_pause_widget);
		} else {
			views.setImageViewResource(R.id.bt_pause_play_widget,
					R.drawable.bt_play_widget);
		}

		// Link actions buttons to intents
		linkButtons(service, views, playing);

		pushUpdate(service, appWidgetIds, views);
	}

	public void updateThumb(PlayerService service, int[] appWidgetIds,
			Bitmap bitmap) {
		final RemoteViews views = new RemoteViews(service.getPackageName(),
				R.layout.chacha_widget);
		views.setImageViewBitmap(R.id.widget_thumb, bitmap);
		linkButtons(service, views, service.isPlaying());
		pushUpdate(service, appWidgetIds, views);
	}

	/**
	 * Link up various button actions using {@link PendingIntents}.
	 * 
	 * @param playerActive
	 *            True if player is active in background, which means widget
	 *            click will launch {@link MediaPlaybackActivity}, otherwise we
	 *            launch {@link MusicBrowserActivity}.
	 */
	private void linkButtons(Context context, RemoteViews views,
			boolean playerActive) {
		// Connect up various buttons and touch events
		Intent intent;
		PendingIntent pendingIntent;

		final ComponentName serviceName = new ComponentName(context,
				PlayerService.class);

		if (playerActive) {
			intent = new Intent(context, PlayerScreen.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			pendingIntent = PendingIntent
					.getActivity(context, 0 /* no requestCode */, intent, 0 /*
																			 * no
																			 * flags
																			 */);
			views.setOnClickPendingIntent(R.id.widget_thumb, pendingIntent);
		} else {
			if (Appinstant.isLogin) {
				intent = new Intent(context, MainScreen.class);
			} else {
				intent = new Intent(context, SplashScreen.class);
			}
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			pendingIntent = PendingIntent
					.getActivity(context, 0 /* no requestCode */, intent, 0 /*
																			 * no
																			 * flags
																			 */);
			views.setOnClickPendingIntent(R.id.widget_thumb, pendingIntent);
		}

		intent = new Intent(PlayerService.TOGGLEPAUSE_ACTION);
		intent.setComponent(serviceName);
		pendingIntent = PendingIntent.getService(context,
				0 /* no requestCode */, intent, 0 /* no flags */);
		views.setOnClickPendingIntent(R.id.bt_pause_play_widget, pendingIntent);

		intent = new Intent(PlayerService.NEXT_ACTION);
		intent.setComponent(serviceName);
		pendingIntent = PendingIntent.getService(context,
				0 /* no requestCode */, intent, 0 /* no flags */);
		views.setOnClickPendingIntent(R.id.bt_next_widget, pendingIntent);

		intent = new Intent(PlayerService.PREVIOUS_ACTION);
		intent.setComponent(serviceName);
		pendingIntent = PendingIntent.getService(context,
				0 /* no requestCode */, intent, 0 /* no flags */);
		views.setOnClickPendingIntent(R.id.bt_previous_widget, pendingIntent);
	}

}
